<?php

namespace App\Filter;


use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\AbstractContextAwareFilter;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use App\Entity\User;
use Doctrine\ORM\QueryBuilder;
use Doctrine\Persistence\ManagerRegistry;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;

class LoveNoteSearchFilter extends AbstractContextAwareFilter
{
    public function __construct(ManagerRegistry $managerRegistry, ?RequestStack $requestStack = null, LoggerInterface $logger = null, array $properties = null, NameConverterInterface $nameConverter = null)
    {
        parent::__construct($managerRegistry, $requestStack, $logger, $properties, $nameConverter);
    }

    /**
     * Passes a property through the filter.
     */
    protected function filterProperty(string $property, $value, QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null)
    {
        $rootAlias = $queryBuilder->getRootAliases()[0];

        //查询该用户是否绑定了loveUserId
        /** @var User $data */
        $data = $this->managerRegistry->getRepository(User::class)->find($value);
        if (!empty($data->getBindId())){
            $queryBuilder->where( $queryBuilder->expr()->in("{$rootAlias}.userId", ':ids'))
                ->setParameter("ids", [$data->getBindId(), $value]);
        }else{
            $queryBuilder->where($queryBuilder->expr()->eq("{$rootAlias}.userId", ":id"))
                ->setParameter(":id", $value);
        }
    }

    public function getDescription(string $resourceClass): array
    {
        if (!$this->properties) {
            return [];
        }
        $description = [];
        foreach ($this->properties as $property => $strategy) {
            $description[$property] = [
                'property' => $property,
                'type' => 'string',
                'required' => true,
                'openapi' => [
                    'description' => '用户id'
                ]
            ];
        }
        return $description;
    }
}